package hr.ctg.domain.action.korisnik;

import hr.ctg.domain.model.Korisnik;

import javax.faces.application.FacesMessage;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.NoResultException;

import org.hibernate.validator.Email;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.faces.Renderer;

@Name("retrievePasswordAction")
public class RetrievePasswordAction {
	@Email
	private String email;

	@In
	EntityManager entityManager;

	@In
	Renderer renderer;

	@In
	FacesMessages facesMessages;

	public void send() {
		Korisnik korisnik;
		try {
			korisnik = (Korisnik) entityManager.createNamedQuery(
					"Korisnik.findByEmail").setParameter(1, email)
					.getSingleResult();
		} catch (final EntityNotFoundException e) {
			facesMessages.addToControlFromResourceBundle("retrieveMessage",
					FacesMessage.SEVERITY_ERROR,
					"message.user.email.dont.exists", email);
			return;
		} catch (final NoResultException e) {
			facesMessages.addToControlFromResourceBundle("retrieveMessage",
					FacesMessage.SEVERITY_ERROR,
					"message.user.email.dont.exists", email);
			return;
		}
		Contexts.getEventContext().set("korisnik", korisnik);
		renderer.render("/templates/mail/password.xhtml");
		facesMessages.addToControlFromResourceBundle("retrieveMessage",
				"message.inf.login.email.sent");

		email = "";

	}

	public String getEmail() {
		return email;
	}

	public void setEmail(final String email) {
		this.email = email;
	}
}
